<template>
	<div>
		<el-scrollbar height="400px" width="80%">
		    <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" highlight-current accordion></el-tree>
		</el-scrollbar>			
	</div>
</template>

<script setup>
import * as GoodsAPI from '@/api/goods.js';
import * as CategoryAPI from '@/api/category.js';

import { ref, defineProps, onMounted, watch, getCurrentInstance } from 'vue';

const props = defineProps({
	modelValue: Number
});
const emit = defineEmits(['update:modelValue']);

const data = ref([]); //数据结构参见官网
const defaultProps = ref({
	// 参见官网文档
	children: 'children',
	label: 'label'
});

const initData = async () => {
	console.log('initData()....');
	// 获取分类信息数据，
	let result = await CategoryAPI.getList();
	let categoryList = result.data;
	// 生成树形控件的属性data数据，数据结构见官网
	for (let i = 0; i < categoryList.length; i++) {
		let category = { id: categoryList[i].id, label: categoryList[i].name };
		result = await GoodsAPI.getPage({ categoryId: category.id, pageSize: 10000000 });
		let goodsList = result.data.list;
		let children = [];
		goodsList.forEach(item => {
			let title = item.name;
			if(title.length > 36 ){
				title = title.substring(0,50) + "..."
			}
			children.push({ id: item.id, label: item.id + '-' + title });
		});
		category.children = children;
		data.value.push(category);
	}
};
initData();

const handleNodeClick = (data, node) => {
	if (node && node.level == 2) {
		emit('update:modelValue', data.id);
	}
};
</script>

<style></style>
